package top.ed333.mcplugins.configurableevents.requirement;

import org.bukkit.event.Event;
import org.jetbrains.annotations.NotNull;

import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.Consumer;

public class ReqGroups implements Iterable<ReqGroup> {
    private final List<ReqGroup> reqGroups;
    private final List<String> orTypes;
    private final List<String> andTypes;

    public ReqGroups(List<ReqGroup> reqGroups, List<String> orTypes, List<String> andTypes) {
        this.reqGroups = reqGroups;
        this.orTypes = orTypes;
        this.andTypes = andTypes;
    }

    public boolean checkReqs(Event event) {
        boolean orResult = false;
        boolean andResult = true;

        for (ReqGroup reqGroup : reqGroups) {
            if (orTypes.contains(reqGroup.getGroupName()) && reqGroup.checkReq(event)) {
                orResult = true;
            }

            if (andTypes.contains(reqGroup.getGroupName()) && !reqGroup.checkReq(event)) {
                andResult = false;
            }
        }
        return orResult && andResult;
    }

    @NotNull
    @Override
    public Iterator<ReqGroup> iterator() {
        return new ReqGroupsIterator(reqGroups);
    }

    private static final class ReqGroupsIterator implements Iterator<ReqGroup> {
        private final List<ReqGroup> data;
        private int index = 0;

        private ReqGroupsIterator(List<ReqGroup> data) {
            this.data = data;
        }

        @Override
        public boolean hasNext() {
            return index < data.size();
        }

        @Override
        public ReqGroup next() {
            if (hasNext()) {
                return data.get(index++);
            } else {
                throw new NoSuchElementException();
            }
        }
    }
}
